package com.apes.fn.server.workDesk.smartHelper.process;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.report.util.SalesReportUtils;
import com.apes.fn.server.workDesk.smartHelper.repository.SmartHelperDao;
import com.apes.fn.server.workDesk.utils.SmartHelperUtils;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apestech.framework.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StopWatch;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @program: apes-server
 * @description:
 * @author: czs
 * @create: 2023-06-14 17:22
 **/
public class CommonSmartDataProcess extends DomainService implements SmartHelperProcess {

    @Autowired
    public SmartHelperDao smartHelperDao;

    protected static final List<String> LEVEL_LIST =  Arrays.asList("smartHelper");

//    public static final String TO_BE_INVOICED = "ZK000752"; // 待开单
//    public static final String IN_STORE_ID= "ZK000754"; // 在店
//    public static final String IN_THE_INNER_ASSOCIATION = "ZK000755"; // 内协中
//    public static final String TO_BE_DELIVERED = "ZK000753"; // 待交车
//    public static final String UNSETTLED_DELIVERY = "ZK000756"; // 未结算交车
//    public static final String STATEMENT_DELIVERY = "ZK000757"; // 结单交车
//    public static final String FINISH = "ZK000758"; // 结束

    @Override
    public List<String> getLevelList() {
        return this.LEVEL_LIST;
    }

    public SmartHelperDao getSmartHelperDao() {
        if (this.smartHelperDao==null){
            this.smartHelperDao = SpringManager.getBean(SmartHelperDao.class);
        }
        return this.smartHelperDao;
    }

    @Override
    public ConcurrentHashMap clearInvalidData(ConcurrentHashMap resultData) {
//        resultData.get("data")
        if (resultData.containsKey("data")){
            Object data = resultData.get("data");
            if (data==null)resultData =null;
            if (data instanceof JSONArray){
                JSONArray jsonArray = (JSONArray) data;
                if (jsonArray.isEmpty()){
                    resultData =null;
                }
            }else if (data instanceof com.alibaba.fastjson.JSONArray){
                com.alibaba.fastjson.JSONArray jsonArray = (com.alibaba.fastjson.JSONArray) data;
                if (jsonArray.isEmpty()){
                    resultData =null;
                }
            }else if (data instanceof List){
                List jsonArray = (List) data;
                if (jsonArray.isEmpty()){
                    resultData =null;
                }
            }else {
                throw new RuntimeException("data必须是数组");
            }
        }else {
            Object items = resultData.get("items");
            if (items==null){
                resultData =null;
            }else if (items instanceof JSONArray){
                JSONArray jsonArray = (JSONArray) items;
                if (jsonArray.isEmpty())resultData =null;
            }else if (items instanceof List){
                List jsonArray = (List) items;
                if (jsonArray.isEmpty())resultData =null;
            }else {
                throw new RuntimeException("items必须是数组:");
            }
        }
        return resultData;
    }

    @Override
    public boolean support(String type) {
        return true;
    }

    public ConcurrentHashMap process(JSONObject param) {
//        StopWatch sw = new StopWatch();
//        sw.start();
        JSONObject onlyParam = new JSONObject(param);
        List<CommonSmartDataProcess> nextProcess = SmartHelperProcessFactory.getCommonSmartDataProcessNextLevel(this);
        //查询当前节点数据
        ConcurrentHashMap resultData = filterNullKeyToConcurrentHashMap(findResultData(param));

        //排序字段
        resultData.put("weightValue",findWeightValue());
        //把查询条件带入返回结果 一般只有部门编码
//        resultData.putAll(onlyParam);
        //添加跳转菜单信息
        appendStyleData(resultData);
        List<Map> nextList;
        //查询下一节点数据
        if (getLevelList().size()==3){
            nextList = nextProcess.parallelStream().map(c -> c.process(param)).filter(Objects::nonNull).collect(Collectors.toList());
        }else {
            nextList = nextProcess.stream().map(c -> c.process(param)).filter(Objects::nonNull).collect(Collectors.toList());
        }
        if (!nextList.isEmpty()){
            List<Map> mapList = nextList.stream()
                    .sorted(Comparator.comparing(o -> ((Integer) o.get("weightValue"))))
                    .collect(Collectors.toList());
            resultData.put("items",mapList );
        }
        //清除无效数据
        resultData = clearInvalidData(resultData);
//        sw.stop();
//        System.out.println(getName()+"执行总耗时:"+sw.getLastTaskTimeMillis());
        return resultData;
    }

    public String getName() {
        return "智能店助";
    }

    public Map findResultData(JSONObject resultMap) {
        return mapper(
                "id", getLevelList().get(getLevelList().size() - 1),
                "name", getName()
        );
    }

    public ConcurrentHashMap filterNullKeyToConcurrentHashMap(Map<String,Object> m){
        ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap<>();
        m.entrySet().stream().filter(a -> a.getValue() != null).forEach(a ->{
            concurrentHashMap.put(a.getKey(),a.getValue());
        });
        return concurrentHashMap;
    }

    public Map appendStyleData(Map resultData){
        SmartHelperUtils.findJumpPageData(resultData);
        return resultData;
    }

    @Override
    public List<CommonSmartDataProcess> findNextProcess(List<CommonSmartDataProcess> commonSmartDataProcessList) {
        List<String> levelList = getLevelList();
        return commonSmartDataProcessList.stream()
                .filter(commonSmartDataProcess ->
                        commonSmartDataProcess.getLevelList().size() == levelList.size() + 1 &&
                                commonSmartDataProcess.getLevelList().get(levelList.size() - 1).equals(levelList.get(levelList.size() - 1))
                )
                .collect(Collectors.toList());
    }

    @Override
    public CommonSmartDataProcess findLastProcess(List<CommonSmartDataProcess> commonSmartDataProcessList) {
        List<String> levelList = getLevelList();
        if (levelList.isEmpty()) return null;
        List<CommonSmartDataProcess> lastProess = commonSmartDataProcessList.stream()
                .filter(commonSmartDataProcess -> commonSmartDataProcess.getLevelList().size() == levelList.size() - 1 &&
                        commonSmartDataProcess.getLevelList().get(commonSmartDataProcess.getLevelList().size() - 1).equals(levelList.get(levelList.size() - 2)))
                .collect(Collectors.toList());
        if (lastProess.isEmpty()) return null;
        if (lastProess.size() > 1) throw new RuntimeException("多个上级,配置有误");
        return lastProess.get(0);
    }

    public Integer findWeightValue(){
        return 0;
    }
}
